﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.Supervise.IBLL;
using System.Data;
using HZ.Supervise.Model;
using HZ.Supervise.Model.Enum;

namespace HZ.Supervise.Web.Admin
{
    public partial class UserUpdate : BasePage
    {

        IBLL_User iu = HZ.Supervise.BLLFactory.BLL_User();

        //保存操作集合 以备二级绑定时使用
        DataTable _mianUserOperateTable;
        protected void Page_Load(object sender, EventArgs e)
        {
            string userId = Request.QueryString["uid"];

            //核心页面，使用强制权限限定
            if (!CurrentAccount.GetUser().IsAdmin)
            {
                PageError("您不是管理员，不能设置权限！", "ChildUserList.aspx");
                return;
            }

            if (!this.IsPostBack)
            {
                //获取用户基本信息
                User childUser = iu.GetUserInfoByUserID(userId);

                if (childUser != null)
                {
                    lblUserId.Text = childUser.UserID;
                    lblUserName.Text = childUser.UserName;

                    //当前登录用户即是其主用户
                    User mainUser = CurrentAccount.GetUser();

                    //用户上级主用户的操作权限
                    IList<OperatingRule> mainUserOperateList = iu.GetUserOperatingRuleSpecial(mainUser.UserID);
                    //用户自己的操作权限
                    IList<OperatingRule> userOperateList = iu.GetUserOperatingRuleSpecial(childUser.UserID);

                    //转换成DataTable
                    _mianUserOperateTable = HZ.Data.ModelConvert.GetDataTableFromModel(mainUserOperateList);
                    DataTable userOperateTable = HZ.Data.ModelConvert.GetDataTableFromModel(userOperateList);
                    userOperateTable.PrimaryKey = new DataColumn[] { userOperateTable.Columns["OperatingRuleID"] };

                    //添加自定义列 合并二张table
                    _mianUserOperateTable.Columns.Add(new DataColumn("IsUsers", typeof(System.Boolean)));
                    foreach (DataRow row in _mianUserOperateTable.Rows)
                    {
                        row["IsUsers"] = userOperateTable.Rows.Contains(row["OperatingRuleID"]);
                    }

                    //分组以获得模块列表
                    DataTable tableModule = _mianUserOperateTable.DefaultView.ToTable(true, "Module");
                    //添加模块枚举值列
                    tableModule.Columns.Add(new DataColumn("ModuleValue", typeof(System.Int32)));
                    foreach (DataRow row in tableModule.Rows)
                    {
                        row["ModuleValue"] = EnumParse.GetModule((int)row["Module"]);
                    }

                    //按模块枚举值排序
                    DataView dv = new DataView(tableModule);
                    dv.Sort = "ModuleValue asc";

                    this.rptModule.DataSource = dv;
                    this.rptModule.DataBind();

                }
                else
                {
                    PageError("用户不存在", "ChildUserList.aspx");
                }
            }
        }
        /// <summary>
        /// 绑定rptOperate
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rptModule_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataTable table;

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                table = this._mianUserOperateTable;
                if (table.Rows.Count > 0)
                {
                    DataView dv = new DataView(table);
                    dv.RowFilter = "Module ='" + DataBinder.Eval(e.Item.DataItem, "Module").ToString() + "'";
                    //dv.Sort = " OperatingRuleName";
                    Repeater rptStoreSubject = (Repeater)e.Item.FindControl("rptOperate");
                    rptStoreSubject.DataSource = dv;
                    rptStoreSubject.DataBind();
                }
            }
        }

        /// <summary>
        /// 保存设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string userId = Request.QueryString["uid"].ToString();
            User user = new User();
            user.UserID = userId;

            //获取用户的操作权限
            List<OperatingRule> operatingRuleList = new List<OperatingRule>();
            string ids = Request["chkOperate"];
            if (!string.IsNullOrEmpty(ids))
            {
                string[] arraryIds = ids.Split(',');
                foreach (string Item in arraryIds)
                {
                    OperatingRule otr = new OperatingRule();
                    otr.OperatingRuleID = Item;
                    operatingRuleList.Add(otr);
                }
            }

            //更新用户及用户权限
            if (iu.SetUserOperatingRule(userId, operatingRuleList))
            {
                if (iu.GetUserByUserID(userId).IsUserAdmin)
                {
                    PageInfo("用户权限更新成功！", this.ReturnUrl);
                }
                else
                {
                    PageInfo("用户权限更新成功！", this.ReturnUrl);
                }
            }
            else
            {
                PageError("用户权限更新失败！", "");
            }


        }

        /// <summary>
        /// 转换布尔值为checked
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        protected string GetChecked(object obj)
        {
            if (obj.ToString() == true.ToString())
            {
                return "checked";
            }
            return "";
        }
    }
}
